<?php

/**
 * Ignus Framework
 *
 * @author Sergey Palyanov <sergey.palyanov@gmail.com>
 * @link http://code.google.com/p/ignus-php/
 * @license http://apache.org/licenses/LICENSE-2.0
 * @package Ignus
 * @subpackage App
 * @since 0.1
 */

namespace Ignus;

use Ignus\Log\LogManager;
use Ignus\Log\Logger;

/**
 * @package Ignus
 * @subpackage App
 * @since 0.5.4
 */
abstract class Model
{
    /**
     * Entity identifier
     * @var mixed
     */
    private $id;

    /**
     * Fetch entity by identifier
     * @param mixed $id Entity identifier
     * @return array|null
     */
    public static function findById($id)
    {
        $entity = self::makeEntityName(get_called_class());
        return EntityManager::getConnection()->getById($entity, $id);
    }

    /**
     * Fetch entity objects matching given criteria
     * @param array $query
     * @return \Ignus\Db\Query
     * @since 0.8.0
     */
    public static function find(array $query = array())
    {
        $entity = self::makeEntityName(get_called_class());
        return EntityManager::getConnection()->find($entity, $query);
    }

    /**
     * Format class name to entity name
     * @param string $className Full class name
     * @return string Entity name
     */
    public static function makeEntityName($className)
    {
        if (($slash  = strrpos($className, '\\')) === false)
            return $className;
        return substr($className, $slash + 1);
    }

    /**
     * Set entity id
     * @param mixed $id
     * @return void
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * Return entity id
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }
}
